//
//  TimeNotificationClass.m
//  ProjectforHDX
//
//  Created by HDX on 16/5/16.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "TimeNotificationClass.h"

@implementation TimeNotificationClass
/**
 *  获取单例
 *
 *  @return 该类的唯一实例
 */
+ (instancetype)defaultManager{
    
    static TimeNotificationClass *timeNotification = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        timeNotification = [[self alloc] init];
       
    });
    return timeNotification;
}
/**
 *  初始化参数
 */
-(void)setupValue{
    if(self.timeInterval==0){
        self.timeInterval=1;
    }
   if( self.notificationBody.length<1){
       self.notificationBody=@"Go Home";
    }
    
    /**
     *  判断音乐文件是否存在
     */
    if(![UtilCheck compareString:[NSString stringWithFormat:@"%@",self.musicName] ContaincompareString2:@".caf"]){
        self.musicName=UILocalNotificationDefaultSoundName;
    }
    if(!self.nowDate){
        self.nowDate=[NSDate date];
    }
    else{
        
 
        
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        
        NSInteger interval = [zone secondsFromGMTForDate:  self.nowDate];
        
        self.nowDate = [ self.nowDate  dateByAddingTimeInterval:-interval];
        
      
    }
    
    
}

-(NSDateComponents*)toDayisWeekDay:(int)day{
 
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents *comps = [[NSDateComponents alloc] init]  ;
    
    NSInteger unitFlags = NSCalendarUnitYear |NSCalendarUnitMonth | NSCalendarUnitDay|NSCalendarUnitWeekday |NSCalendarUnitHour |NSCalendarUnitMinute | NSCalendarUnitSecond;
 
    comps = [calendar components:unitFlags fromDate: [NSDate dateWithTimeInterval:day*24*60*60 sinceDate:self.nowDate]];
    
    return comps;
    
 
}
/**
 *  添加定时通知
 *
 *  @param stringName 名称
 *  @param day        通知时间
 *  @param isRepeat      是否重复
 *
 *  @return 返回是否成功
 */
-(BOOL)addTileNotificationName:(NSString*)stringName {
    [self setupValue];
    NSInteger count=1;
    if(self.forweekDay){
        count=7;
    }
    
    for(int i=0;i<count;i++){
        //清理旧的定时通知
     [self removeTileNotificationName:stringName LocalTag:self.Ntag];
        NSDateComponents *comps=[self toDayisWeekDay:i];
        
        if( comps.weekday==1||comps.weekday==7){
             continue;
        }
        
     self.timeInterval= 24*(3600)*i+self.hour*3600+self.minute*60+self.second;
        
    UILocalNotification *notification=[[UILocalNotification alloc] init];
    if (notification!=nil) {//判断系统是否支持本地通知
        
        // 设置提醒时间，倒计时以秒为单位。以下是从现在开始55秒以后通知
        notification.fireDate= [NSDate dateWithTimeIntervalSince1970:self.timeInterval];
        // 设置时区，使用本地时区
        notification.timeZone=[NSTimeZone defaultTimeZone];
        notification.repeatInterval=self.calendarType;//
        notification.alertBody=[NSString stringWithFormat:@"%@",self.notificationBody];//弹出的提示信息
        notification.applicationIconBadgeNumber=[[[UIApplication sharedApplication] scheduledLocalNotifications] count]+self.badgeNumber; //应用程序的右上角小数字
        if(self.musicName.length>1){
        
        }else{
            
        }
        notification.soundName=  self.musicName;//本地化通知的声音
        
        NSString *actionString=[NSString stringWithFormat:@"%@",self.alertAction];
        
        notification.alertAction = NSLocalizedString(actionString,@"Dear");  //弹出的提示框按钮
        
        notification.hasAction =self.hasAction;
        if(self.repeatTime!=0){
            [self.userDict setObject:[NSNumber numberWithInteger:self.repeatTime] forKey:@"repeatTime"];
        }
        
        if(self.userDict){
            notification.userInfo=self.userDict;
        }
        else{
            if(self.repeatTime!=0){
                notification.userInfo=[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:self.Ntag],stringName,[NSNumber numberWithInteger:self.repeatTime],@"repeatTime",nil];
            }
            else{
                notification.userInfo=[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:self.Ntag],stringName,nil];
            }
        }
        
 
        /**
         *   ios8后，需要添加这个注册，才能得到授权
         *
         *  @param
         *
         *  @return
         */
        if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                     categories:nil];
            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
            // 通知重复提示的单位，可以是天、周、月
            notification.repeatInterval = NSCalendarUnitDay;
        } else {
            // 通知重复提示的单位，可以是天、周、月
            notification.repeatInterval = NSCalendarUnitDay;
        }
        
      
        
        /**
         *  是否立即通知
         */
        if(self.ispresentLocalNotificationNow){
                    //立即通知
            [[UIApplication sharedApplication] presentLocalNotificationNow:notification];
        }
        else{
             [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        }
      

        
    }
        
    }
    
    return YES;
}

/**
 *  按名称删除通知
 *
 *  @param stringName 名称
 *
 *  @return 返回是否成功
 */
-(BOOL)removeTileNotificationName:(NSString*)stringName  LocalTag:(NSInteger)tag{
    
    NSArray *nArry=[[UIApplication sharedApplication] scheduledLocalNotifications];
    
    NSUInteger acount=[nArry count];
    if (acount>0)
    {
        // 遍历找到对应nfkey和notificationtag的通知
        for (int i=0; i<acount; i++)
        {
            UILocalNotification *myUILocalNotification = [nArry objectAtIndex:i];
            NSDictionary *userInfo = myUILocalNotification.userInfo;
            NSNumber *obj = [userInfo objectForKey:stringName];
            int mytag=[obj intValue];
            if (mytag==tag)
            {
                // 删除本地通知
                [[UIApplication sharedApplication] cancelLocalNotification:myUILocalNotification];
                return YES;
            }
        }
    }
    
    
    return NO;
}

@end
